package bosc.cn.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;


public class SerialNoGenerator {

    private static final Random RANDOM = new Random();
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter DATETIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    // 消费方流水号：自增计数器
    private static final AtomicLong COUNTER = new AtomicLong(1);

    // 申请单号：当日自增计数器（每日重置）
    private static final AtomicInteger APPLY_DAILY_COUNTER = new AtomicInteger(1);

    /**
     * 生成全渠道流水号（28位）
     * 格式：yyyyMMddHHmmss + channelCode(4) + seq(10)
     */
    public static String generateGlblSrlNo(String channelCode) {
        String timePart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        long seq = COUNTER.getAndIncrement() % 10000000000L; // 保证10位
        return timePart + String.format("%04d", Integer.parseInt(channelCode)) + String.format("%010d", seq);
    }

    /**
     * 生成消费方流水号（28位）
     * 格式：systemCode(4) + yyyyMMddHHmmss + seq(10)
     */
    public static String generateCnsmrSrlNo(String systemCode) {
        String timePart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        long seq = COUNTER.getAndIncrement() % 10000000000L;
        return String.format("%04d", Integer.parseInt(systemCode)) + timePart + String.format("%010d", seq);
    }

    /**
     * 生成申请单号
     * @param businessType 业务类型（"DK"=贷款，"ZZ"=转账）
     */
    private static final AtomicInteger DAILY_COUNTER = new AtomicInteger(0);
    private static String currentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

    public static synchronized String generateApplyNo(String businessType) {
        String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 如果跨天，重置计数器
        if (!today.equals(currentDate)) {
            currentDate = today;
            DAILY_COUNTER.set(0);
        }

        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int sequence = DAILY_COUNTER.incrementAndGet();

        // 固定流水号长度为 6 位就够用了（支持每天 999,999 个）
        return String.format("%s%s%06d", businessType, dateTime, sequence);
    }



}

